<template>
        <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form :model="paramsForm" label-width="auto">                    
                    <el-form-item label="年份:" size="small">
                        <el-config-provider>
                            <el-select v-model="paramsForm.jcYear" 
                                placeholder="请选择年份" size="small" style="width: 80px"   
                                @visible-change="getYears"                    
                            >
                                <el-option v-for="item in yearsArr" :label="item" :value="item" :key="item"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="线路:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.lines" 
                                clearable
                                placeholder="可留空" size="small" style="width: 110px"
                                multiple
                                collapse-tags
                                collapse-tags-tooltip                                
                                @change="changeLines"  
                                @visible-change="getLines"                      
                            >
                                <template #header>
                                    <el-checkbox
                                        v-model="lineCheckAll"
                                        :indeterminate="lineIndeterminate"
                                        @change="lineHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <!-- <el-option label="" :value="''" /> -->
                                <el-option v-for="item in linesAndStationsArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="站点:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.stations" 
                                multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip
                                placeholder="可留空" size="small" style="width: 130px"
                                @change="changeStations"                      
                            >
                            <template #header>
                                    <el-checkbox
                                        v-model="stationCheckAll"
                                        :indeterminate="stationIndeterminate"
                                        @change="stationHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <!-- <el-option label="" :value="''" /> -->
                                <el-option v-for="item in stationsArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="专业:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.specialties" 
                                clearable
                                placeholder="可留空" size="small" style="width: 120px"
                                multiple
                                collapse-tags
                                collapse-tags-tooltip 
                                @visible-change="getSpecialties" 
                                @change="changeSpecialies"                       
                            >
                            <template #header>
                                    <el-checkbox
                                        v-model="specCheckAll"
                                        :indeterminate="specIndeterminate"
                                        @change="specHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <!-- <el-option label="" :value="''" /> -->
                                <el-option v-for="item in specialtiesArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="子系统:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.subsys" 
                                multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip
                                placeholder="可留空" size="small" style="width: 130px"
                                @change="changeSubsys"                                             
                            >
                                <template #header>
                                    <el-checkbox
                                        v-model="subCheckAll"
                                        :indeterminate="subIndeterminate"
                                        @change="subHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <!-- <el-option label="" :value="''" /> -->
                                <el-option v-for="item in subsysArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="完成状态:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.isFinish" 
                                clearable
                                placeholder="可留空" size="small" style="width: 100px"                       
                            >
                                <el-option v-for="item in isFinishArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="单据状态:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.status" 
                                clearable
                                placeholder="可留空" size="small" style="width: 100px"                       
                            >
                                <el-option v-for="item in statusArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="描述:" size="small">
                        <el-input v-model="paramsForm.description" size="small" style="width: 100px"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getJcDatas(paramsForm)"
                        :loading = "loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control 
                :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow"
                :permObj="permObj"
                @addClick="editJcData('add',{})" 
                @showDownload="showDownloadBox"                               
                @downloadExcelPaging="downloadExcelPaging(newDatasArr,'jcDataTable','检测记录信息')"
                @downloadExcelAll="downloadExcelAll(datasArr,'检测记录信息')"
                @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel',selectJcDatas)"
                @batchUpload="batchUpload"
            >
                <template #default>
                    <el-button type="warning" plain size="small" title="批量变更状态" 
                        v-show="batchIsShow" 
                        v-perm="permObj.update"
                        @click="editJcData('batchChangeStatus',selectJcDatas)"
                    >
                        <el-icon><EditPen /></el-icon>
                    </el-button>
                    <span class="batchChangeStatus" v-show="batchIsShow" 
                        v-perm="permObj.update"
                    >须变更的状态：</span>
                    <el-select v-model="newStatus" 
                        size="small" style="width: 80px" 
                        v-show="batchIsShow"  
                        v-perm="permObj.update"                     
                    >
                        <el-option v-for="item in statusArr" :label="item.label" :value="item.value" :key="item.value"/>
                    </el-select>
                    <el-button type="warning" plain size="small" title="提交" class="submit-btn"
                        v-show="batchIsShow" 
                        v-perm="permObj.update"
                        @click="editSubmit('batchChangeStatus',changeDatasArrs)"
                    >
                        提交
                    </el-button>
                </template>
            </Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage"
                v-model:pageSize="pageSize"
                @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)"
                @toFirst="toFirstPage"
                @toEnd="toEndPage"
                @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"
            ></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%"  v-loading="loading" 
                @selection-change="handleSelectionChange"
                id="jcDataTable"
            >
                <el-table-column type="selection" width="50" v-if="selectShow"/>
                <el-table-column fixed prop="WONUM" label="WONUM" width="90" />
                <el-table-column fixed prop="DESCRIPTION" label="描述" width="150" />
                <el-table-column prop="AREA" label="作业区域" width="120" />
                <el-table-column prop="AREA2" label="作业区域2" width="120" />
                <el-table-column prop="ISPASS" label="是否通过" width="60" />
                <el-table-column prop="FINISHDATE" label="实际完成日期" width="120" >
                    <template #default="{row}">
                        {{ dateFormat(row.FINISHDATE) }}
                    </template>
                </el-table-column>  
                <el-table-column prop="PERSON" label="配合人" width="80" />
                <el-table-column prop="PERSON2" label="配合人2" width="80" />
                <el-table-column prop="PERSON3" label="配合人3" width="80" />
                <el-table-column prop="REMARK" label="备注" width="120" />
                <el-table-column prop="CUST_LINENUM" label="线路" width="60" />
                <el-table-column prop="CUST_SPECNUM" label="专业" width="60" />
                <el-table-column prop="SPEC_DESC" label="专业名称" width="60" />
                <el-table-column prop="CUST_SUBSYS" label="子系统" width="80" />
                <el-table-column prop="SUB_DESC" label="子系统名称" width="120" />
                <el-table-column prop="LOCATION" label="站点" width="80" />
                <el-table-column prop="PERSONGROUP" label="作业工班" width="120" />
                <el-table-column prop="PGNAME" label="班组名称" width="130" />
                <el-table-column prop="SCHEDFINISH" label="计划完成日期" width="120" >
                    <template #default="{row}">
                        {{ dateFormat(row.SCHEDFINISH) }}
                    </template>
                </el-table-column>
                <el-table-column prop="DEVICENUM" label="设备编号" width="170" />
                <el-table-column prop="SBDESC" label="现场设备描述" width="150" /> 
                <el-table-column prop="STATUS" label="状态" width="60" />               
                <el-table-column fixed="right" label="Operations" min-width="180"
                    v-perm="permObj.update"
                >
                    <template #default="{row}">
                        <el-button type="primary" size="small" 
                            @click="editJcData('update',row)" title="编辑"
                            v-perm="permObj.update"
                        >
                            <el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button type="warning" size="small" 
                            @click="editJcData('copy',row)" title="复制"
                            v-perm="permObj.add"
                        >
                            <el-icon><CopyDocument /></el-icon>
                        </el-button>
                        <el-button  type="danger" size="small" class="del" title="删除" 
                            @click="editSubmit('delete',row)"
                            v-perm="permObj.delete"
                        >
                            <el-icon><DeleteFilled /></el-icon>
                        </el-button>
                    </template>
                </el-table-column>               
            </el-table>
        </template>    
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" 
        @submit="editSubmit(submitType,editForm)"
        @cancel-submit="resetForm"
    >
        <el-form :model="editForm"  
            ref="updateFormRef"
            :rules="rules"
        >
            <el-form-item label="WONUM" :label-width="formLabelWidth">
                <el-input v-model="editForm.WONUM" autocomplete="off" disabled/>
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" prop="DESCRIPTION">
                <el-input v-model="editForm.DESCRIPTION" autocomplete="off" />
            </el-form-item>
            <el-form-item label="作业区域" :label-width="formLabelWidth" prop="AREA">
                <el-input v-model="editForm.AREA" autocomplete="off" />
            </el-form-item>
            <el-form-item label="作业区域2" :label-width="formLabelWidth" prop="AREA2"> 
                <el-input v-model="editForm.AREA2" autocomplete="off" />
            </el-form-item>
            <el-form-item label="是否通过" :label-width="formLabelWidth" > 
                <!-- <el-input v-model="editForm.ISPASS" autocomplete="off" /> -->
                <el-select v-model="editForm.ISPASS" 
                    placeholder="不可留空"                                                     
                >
                    <el-option label="通过" value="通过" key="通过"/>
                    <el-option label="不通过" value="不通过" key="不通过"/>
                </el-select>
            </el-form-item>
            <el-form-item label="实际完成日期" :label-width="formLabelWidth" >
                <el-date-picker
                    v-model="editForm.FINISHDATE"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item label="配合人" :label-width="formLabelWidth" > 
                <el-input v-model="editForm.PERSON" autocomplete="off" />
            </el-form-item>
            <el-form-item label="配合人2" :label-width="formLabelWidth" >
                <el-input v-model="editForm.PERSON2" autocomplete="off" />
            </el-form-item>
            <el-form-item label="配合人3" :label-width="formLabelWidth" >
                <el-input v-model="editForm.PERSON3" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth" >
                <el-input v-model="editForm.REMARK" autocomplete="off" />
            </el-form-item>
            <el-form-item label="线路" :label-width="formLabelWidth" prop="CUST_LINENUM">
                <el-select v-model="editForm.CUST_LINENUM" 
                    placeholder="不可留空"                                 
                    @change="changeLines"  
                    @visible-change="getLines"                      
                >
                    <el-option v-for="item in linesAndStationsArr" :label="item.value" :value="item.value" :key="item.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="专业" :label-width="formLabelWidth" prop="CUST_SPECNUM">
                <el-select v-model="editForm.CUST_SPECNUM" 
                    placeholder="不可留空" 
                    @visible-change="getSpecialties" 
                    @change="changeSpecialies"                       
                >                        
                    <el-option v-for="item in specialtiesArr" :label="item.value" :value="item.value" :key="item.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="专业名称" :label-width="formLabelWidth" >
                <el-input v-model="editForm.SPEC_DESC" autocomplete="off" disabled/>
            </el-form-item>
            <el-form-item label="子系统" :label-width="formLabelWidth" prop="CUST_SUBSYS">
                <el-select v-model="editForm.CUST_SUBSYS" 
                    placeholder="不可留空"  
                    @change="changeSubsys"                                        
                >
                    <el-option v-for="item in subsysArr" :label="item.value" :value="item.value" :key="item.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="子系统名称" :label-width="formLabelWidth" >
                <el-input v-model="editForm.SUB_DESC" autocomplete="off" disabled/>
            </el-form-item>
            <el-form-item label="站点" :label-width="formLabelWidth" prop="LOCATION">
                <el-select v-model="editForm.LOCATION" 
                    placeholder="不可留空"                      
                >
                    <el-option v-for="item in stationsArr" :label="item.label" :value="item.value" :key="item.value"/>
                </el-select>                
            </el-form-item>
            <el-form-item label="作业工班" :label-width="formLabelWidth" prop="PERSONGROUP">
                <el-select v-model="editForm.PERSONGROUP" 
                    placeholder="不可留空" 
                    @visible-change="getPgs"    
                    @change="changePgs"                   
                >                        
                    <el-option v-for="item in useStore.pgs" :label="item.value" :value="item.PERSONGROUP" :key="item.PERSONGROUP"/>
                </el-select>
            </el-form-item>
            <el-form-item label="班组名称" :label-width="formLabelWidth" >
                <el-input v-model="editForm.PGNAME" autocomplete="off" disabled/>
            </el-form-item>
            <el-form-item label="计划完成日期" :label-width="formLabelWidth" >
                <el-date-picker
                    v-model="editForm.SCHEDFINISH"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item label="设备编号" :label-width="formLabelWidth" >
                <el-input v-model="editForm.DEVICENUM" autocomplete="off" />
            </el-form-item>
            <el-form-item label="现场设备描述" :label-width="formLabelWidth" >
                <el-input v-model="editForm.SBDESC" autocomplete="off" />
            </el-form-item>
            <el-form-item label="状态" :label-width="formLabelWidth" prop="STATUS">
                <el-select v-model="editForm.STATUS" placeholder="请选择状态">
                    <el-option v-for="item in statusArr" :label="item.label" :value="item.value" :key="item.value"/>
                </el-select>
            </el-form-item>
      </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys"
        @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate',uploadTable)"
        @batchAdd="editSubmit('batchAdd',uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table','检测记录导入模板')"
    > 
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <el-table-column fixed prop="WONUM" label="WONUM" width="90" />
                <el-table-column fixed prop="DESCRIPTION" label="描述" width="150" />
                <el-table-column prop="AREA" label="作业区域" width="120" />
                <el-table-column prop="AREA2" label="作业区域2" width="120" />
                <el-table-column prop="ISPASS" label="是否通过" width="60" />
                <el-table-column prop="FINISHDATE" label="实际完成日期" width="120" >
                    <template #default="{row}">
                        {{ row.FINISHDATE === "" ? "" : dateFormat(row.FINISHDATE) }}
                    </template>
                </el-table-column>  
                <el-table-column prop="PERSON" label="配合人" width="80" />
                <el-table-column prop="PERSON2" label="配合人2" width="80" />
                <el-table-column prop="PERSON3" label="配合人3" width="80" />
                <el-table-column prop="REMARK" label="备注" width="120" />
                <el-table-column prop="CUST_LINENUM" label="线路" width="60" />
                <el-table-column prop="CUST_SPECNUM" label="专业" width="60" />
                <el-table-column prop="SPEC_DESC" label="专业名称" width="60" />
                <el-table-column prop="CUST_SUBSYS" label="子系统" width="80" />
                <el-table-column prop="SUB_DESC" label="子系统名称" width="120" />
                <el-table-column prop="LOCATION" label="站点" width="80" />
                <el-table-column prop="PERSONGROUP" label="作业工班" width="120" />
                <el-table-column prop="PGNAME" label="班组名称" width="130" />
                <el-table-column prop="SCHEDFINISH" label="计划完成日期" width="120" >
                    <template #default="{row}">
                        {{ dateFormat(row.SCHEDFINISH) }}
                    </template>
                </el-table-column>
                <el-table-column prop="DEVICENUM" label="设备编号" width="170" />
                <el-table-column prop="SBDESC" label="现场设备描述" width="150" /> 
                <el-table-column prop="STATUS" label="状态" width="60" />         
        </el-table>
    </Dialog>
</template>

<script setup>
import { ref, reactive ,watch} from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Paging from '@/components/Paging.vue'
import Control from '@/components/Control.vue'
import Dialog from '@/components/Dialog.vue'
import Drawer from '@/components/Drawer.vue'
import { paging } from '@/utils/paging'
import { getLinesInfo , getSpecialtiesInfo } from '@/utils/xfjcApi/device'
import { getJcDataInfo , changeJcDataStatus , editJcDatas , editManyJcDatas} from '@/utils/xfjcApi/jcData'
import { xfjcStore } from '@/stores/jcStore'
import { mainStore } from '@/stores/store'
import { dateFormat } from '@/utils/dateFormat'
import { exportClickFromTableId , exportClickFromDatas } from '@/utils/downloadExcel'
import { msgOpen } from '@/utils/msg'
import { getPg } from '@/utils/adminApi/usrs'
import { objCopy } from '@/utils/objCopy'
import {confirm ,confirmBatch} from '@/utils/confirm'

let useJcStore = xfjcStore()
let useStore = mainStore()

//权限对象--用于控制按钮显示
const permObj = {
    add:{name:'JcdataSearch',type:'add'},
    update:{name:'JcdataSearch',type:'update'},
    delete:{name:'JcdataSearch',type:'delete'}
}

const {
    datasArr, 
    datasLength,
    firstPage,
    pageSize, 
    countPage,
    newDatasArr, 
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页

//参数
//#region 
/********************************************************************************************************************* */
let yearsArr = ref([])
//线路、站点
let linesAndStationsArr = ref([])
let lineCheckAll = ref(false)
let lineIndeterminate = ref(false) //设置不确定状态，仅负责样式控制
let stationsArr = ref([])
let stationCheckAll = ref(false)
let stationIndeterminate = ref(false)

//专业、子系统
let specialtiesArr = ref([])
let specCheckAll= ref(false)
let specIndeterminate= ref(false)
let subsysArr = ref([])
let subCheckAll= ref(false)
let subIndeterminate= ref(false)

//完成状态
let isFinishArr = ref([
    {label: '未完成', value: 0},
    {label: '已完成', value: 1}
])

//单据状态
let statusArr = ref([
   { label: '不使用', value: 0 },
   { label: '在用', value: 1}
])

let paramsForm = reactive({
    jcYear: '',
    lines: [],
    stations: [],
    specialties: [],
    subsys: [],
    isFinish: '',
    status: '',
    description: ''
})
let loading = ref(false)

//年份
const getYears = () => {
    let fullYear = new Date().getFullYear()+2
    let arr = []
    for(let i = 2020; i <= fullYear; i++){
        arr.push(i)
    } 
    yearsArr.value = arr
    // console.log(yearsArr.value)
}

/**
 * location转换为树形
 * @param {Array} arr workType 原数组对象 
 */
 const locationToTree = (arr)=>{
    let line = []
    // 先把线路拿出来
    arr.forEach(item => {
        if(item.AREATYPE === '线路'){
            let lineObj = {
                label: item.DESCRIPTION,
                value: item.LOCATION,
                children: []
            }
            line.push(lineObj)
        }       
    })
    // 再把站点拿出来
    line.forEach(item => {
        arr.forEach(item1 => {
            if(item.value === item1.CUST_LINENUM && item1.AREATYPE !== '线路'){
                let stationObj = {
                    label: item1.DESCRIPTION,
                    value: item1.LOCATION,
                    parent: item.value
                }
                item.children.push(stationObj)
            }
        })
    })
    // console.log(line)
    return line
}

//获取线路站点数据
const getLines = async () => {
 //获取数据
    if(!useJcStore.linesInfo.length){
        let lines = await getLinesInfo()
        if(lines.status){
            linesAndStationsArr.value = locationToTree(lines.resDatas.lines)            
            useJcStore.setLinesInfo(linesAndStationsArr.value)
        }
    }else{
        linesAndStationsArr.value = useJcStore.linesInfo
    }  
}

/**
 * 改变线路联动站点
 * @param val 选中的线路值
 */
const changeLines = (val) => {
    // console.log(val)
    // console.log(typeof val)
    // console.log(Array.isArray(val))    
    //#region  
    //单选   
    if(typeof val === 'string'){
        linesAndStationsArr.value.forEach(item => {
            // console.log(item)            
            if(item.value === val) stationsArr.value =  item.children
        }) 
    }
    //多选 el-select组件多选后使用typeof判断为object，需要使用Array.isArray()才能判断为数组
    if(Array.isArray(val)){
        //每次改变线路时，都要把站点清空
        paramsForm.stations = []
        stationCheckAll.value = false
        stationIndeterminate.value = false
        if(val.length === 1){
            //取消全选
            if(linesAndStationsArr.value.length && val.length !== linesAndStationsArr.value.length) {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            linesAndStationsArr.value.forEach(item => {
                // console.log(item)            
                if(item.value === val[0]) stationsArr.value =  item.children
            })        
        }
        else if(val.length === 0){
            stationsArr.value = [] 
            stationCheckAll.value = false
            stationIndeterminate.value = false
            lineCheckAll.value = false
            lineIndeterminate.value = false
        }  
        else if(val.length > 1){
            // 当val长度大于1切等于线路数组长度时，全选勾选
            if(val.length === linesAndStationsArr.value.length){
                lineCheckAll.value = true 
                lineIndeterminate.value = false
            }else{
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            let staArrss = []
            // 当val长度大于1时，获取站点
            for(let i = 0; i < val.length; i++){
                let staArrs = []
                for(let j = 0; j < linesAndStationsArr.value.length; j++){
                    let staArr = []
                    if(linesAndStationsArr.value[j].value === val[i]){
                        staArr.push(...linesAndStationsArr.value[j].children)   
                        staArrs.push(...staArr)                 
                    }                
                }             
                staArrss.push(...staArrs)                               
            }
            stationsArr.value = staArrss
        }  
    }  
    //#endregion
}

//线路全选
const lineHandleCheckAll = (val) => {
    lineIndeterminate.value = false
    if (val) {
        paramsForm.lines = linesAndStationsArr.value.map((_) => _.value)
        //需要调用changeLines方法，否则会出现选中的线路没有站点的情况
        changeLines(paramsForm.lines) 
    } else {
        paramsForm.lines = []
        //需要调用changeLines方法，否则会出现不选线路后站点仍存在的情况
        changeLines(paramsForm.lines) 
    } 
}

/**
 * 站点变更
 * @param val 选中的站点值
 */
const changeStations = (val) => {
    if(Array.isArray(val)){
        if(val.length === 1){
            //取消全选
            if(stationsArr.value.length && val.length !== stationsArr.value.length) {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            } 
        }
        else if(val.length === 0){
            stationCheckAll.value = false
            stationIndeterminate.value = false
        }
        else if(val.length > 1){
            // 当val长度大于1切等于站点数组长度时，全选勾选
            if(val.length === stationsArr.value.length){
                stationCheckAll.value = true
                stationIndeterminate.value = false  
            } else{
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
    }
}

/**
 * 站点全选
 * @param val 站点全选值
 */
const stationHandleCheckAll = (val) => {
    stationIndeterminate.value = false
    if (val) {
        paramsForm.stations = stationsArr.value.map((_) => _.value)
    } else {
        paramsForm.stations = []
    }
}

/**
 * 专业子系统转换为树形
 * @param spec 专业数组
 * @param sub 子系统数组
 */
const specAndSubToTree = (spec,sub)=>{
    let specArr = []
    spec.forEach(item => {
        let specObj = {
            label: item.SPEC_DESC,
            value: item.CUST_SPECNUM,
            children: []
        }
        specArr.push(specObj)
    })
    sub.forEach(item => {
        specArr.forEach(item1 => {
            if(item1.value === item.CUST_SPECNUM){
                let subObj = {
                    label: item.SUB_DESC,
                    value: item.CUST_SUBSYS,
                    parent: item1.value
                } 
                item1.children.push(subObj)
            } 
        }) 
    })
    // console.log(specArr)
    return specArr
    
}

//获取专业及子系统数据
const getSpecialties = async () => {
    if(!useJcStore.specialtiesInfo.length){
        //获取专业
        let specAndSub = await getSpecialtiesInfo()         
        if(specAndSub.status){
            specialtiesArr.value = specAndSubToTree(specAndSub.resDatas.specialties,specAndSub.resDatas.subsys)            
            useJcStore.setSpecialtiesInfo(specialtiesArr.value)
        }        
    }else{
        specialtiesArr.value = useJcStore.specialtiesInfo 
    }
}

/**
 * 改变专业联动子系统
 * @param val 选中的专业值
*/
const changeSpecialies = (val) => {
    // console.log(typeof val ==='string')
    if(typeof val ==='string'){
        specialtiesArr.value.forEach(item => {
            // console.log(item)
            if(item.value === val) subsysArr.value =  item.children
        })
        editForm.SPEC_DESC = specialtiesArr.value.find(item => item.value === val).label
    }
    if(Array.isArray(val)){      
        //每次改变专业时，都要把子系统清空
        paramsForm.subsys = []
        subCheckAll.value = false
        subIndeterminate.value = false
        if(val.length === 1){
            //取消全选
            if(specialtiesArr.value.length && val.length !== specialtiesArr.value.length) {
                specCheckAll.value = false
                specIndeterminate.value = true
            } 
            specialtiesArr.value.forEach(item => {
                // console.log(item)
                if(item.value === val[0]) subsysArr.value =  item.children 
            })
        }
        else if(val.length === 0){
            subsysArr.value = []
            subCheckAll.value = false
            subIndeterminate.value = false
            specCheckAll.value = false
            specIndeterminate.value = false
        }
        else if(val.length > 1){
            // 当val长度大于1切等于专业数组长度时，全选勾选
            if(val.length === specialtiesArr.value.length){
                specCheckAll.value = true
                specIndeterminate.value = false  
            } else{
                specCheckAll.value = false
                specIndeterminate.value = true
            }
            let subArrss = []
            // 当val长度大于1时，获取子系统
            for(let i = 0; i < val.length; i++){
                let subArrs = []
                for(let j = 0; j < specialtiesArr.value.length; j++){
                    let subArr = []
                    if(specialtiesArr.value[j].value === val[i]){
                        subArr.push(...specialtiesArr.value[j].children)    
                        subArrs.push(...subArr)  
                    }  
                }
                subArrss.push(...subArrs) 
            }
            subsysArr.value = subArrss
        }
    }
}

/**
 * 专业全选
 * @param val 专业全选值
 */
const specHandleCheckAll = (val) => {
    specIndeterminate.value = false
    if (val) {
        paramsForm.specialties = specialtiesArr.value.map((_) => _.value)
        changeSpecialies(paramsForm.specialties)
    } else {
        paramsForm.specialties = []
        changeSpecialies(paramsForm.specialties)
    }
}

/**
 * 子系统变更
 * @param val 选中的子系统值
 */
const changeSubsys = (val) => {
    // console.log(typeof val ==='string');
    
    if(Array.isArray(val)){
        if(val.length === 1){
            //取消全选
            if(subsysArr.value.length && val.length!== subsysArr.value.length) {
                subCheckAll.value = false
                subIndeterminate.value = true
            } 
        }
        else if(val.length === 0){
            subCheckAll.value = false
            subIndeterminate.value = false 
        }
        else if(val.length > 1){
            // 当val长度大于1切等于子系统数组长度时，全选勾选
            if(val.length === subsysArr.value.length){
                subCheckAll.value = true
                subIndeterminate.value = false
            } else{
                subCheckAll.value = false
                subIndeterminate.value = true
            }
        }
    }
    if(typeof val ==='string'){
        editForm.SUB_DESC = subsysArr.value.find(item => item.value === val).label
    }
}

/**
 * 子系统全选
 * @param val 子系统全选值
 */
const subHandleCheckAll = (val) => {
    subIndeterminate.value = false
    if (val) {
        paramsForm.subsys = subsysArr.value.map((_) => _.value)   
    } else {
        paramsForm.subsys = []
    }
}

/**
 * 获取检测数据
 * @param {Object} form 表单参数对象
 */
const getJcDatas = async (form) => {
    if(form.jcYear === ""){
        msgOpen("请选择检测年份")
    }else{
        loading.value = true
        let res = await getJcDataInfo(form)
        pagingPreprocessing(res.resDatas.jcDataInfo) //分页前置处理
        loading.value = false
    }    
}
/************************************************************************************************************ */
//#endregion

//编辑检测记录信息
//#region 
/***************************************************************************************************************************** */
//抽屉样式
let title = ref("")
let size = ref("40%")
let formLabelWidth = ref("110")
let drawerRef = ref(null) //组件ref

//用于存储未修改前检测记录信息
let oldJcData = reactive({
    WONUM:"",
    DESCRIPTION:"",
    AREA:"",
    AREA2:"",
    ISPASS:"",
    FINISHDATE:"",
    PERSON:"",
    PERSON2:"",
    PERSON3:"",
    REMARK:"",
    CUST_LINENUM:"",
    CUST_SPECNUM:"",
    SPEC_DESC:"",
    CUST_SUBSYS:"",
    SUB_DESC:"",
    LOCATION:"",
    PERSONGROUP:"",
    PGNAME:"",
    SCHEDFINISH:"",
    DEVICENUM:"",
    SBDESC:"",
    STATUS:"",    
})
let editForm = reactive({
    WONUM:"",
    DESCRIPTION:"",
    AREA:"",
    AREA2:"",
    ISPASS:"",
    FINISHDATE:"",
    PERSON:"",
    PERSON2:"",
    PERSON3:"",
    REMARK:"",
    CUST_LINENUM:"",
    CUST_SPECNUM:"",
    SPEC_DESC:"",
    CUST_SUBSYS:"",
    SUB_DESC:"",
    LOCATION:"",
    PERSONGROUP:"",
    PGNAME:"",
    SCHEDFINISH:"",
    DEVICENUM:"",
    SBDESC:"",
    STATUS:"",
})
//提交类型
let submitType = ref('')
//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    DESCRIPTION: [
        { required: true, message: '请输入描述', trigger: 'blur' },
    ],
    AREA: [
        { required: true, message: '请输入作业区域', trigger: 'blur' },
    ],
    AREA2: [
        { required: true, message: '请输入作业区域2', trigger: 'blur' },
    ],
    CUST_LINENUM: [
        { required: true, message: '请输入线路', trigger: 'blur' },
    ],
    CUST_SPECNUM: [
        { required: true, message: '请输入专业', trigger: 'blur' },
    ],
    CUST_SUBSYS: [
        { required: true, message: '请输入子系统', trigger: 'blur' },
    ],
    LOCATION: [
        { required: true, message: '请输入站点', trigger: 'blur' },
    ],
    PERSONGROUP: [
        { required: true, message: '请输入所属班组', trigger: 'blur' },
    ],
    STATUS: [
        { required: true, message: '请选择状态', trigger: 'blur' },
    ]
})

//重置表单
const resetForm = ()=>{
    // if(submitType.value === 'update' || submitType.value === 'copy'){
    if(submitType.value === 'update' ){
        editForm = objCopy(oldJcData,editForm)
    }else if(submitType.value === 'add'){
        editForm = reactive({
            WONUM:"",
            DESCRIPTION:"",
            AREA:"",
            AREA2:"",
            ISPASS:"",
            FINISHDATE:"",
            PERSON:"",
            PERSON2:"",
            PERSON3:"",
            REMARK:"",
            CUST_LINENUM:"",
            CUST_SPECNUM:"",
            SPEC_DESC:"",
            CUST_SUBSYS:"",
            SUB_DESC:"",
            LOCATION:"",
            PERSONGROUP:"",
            PGNAME:"",
            SCHEDFINISH:"",
            DEVICENUM:"",
            SBDESC:"",
            STATUS:"",
        })
    }
}

//获取班组信息
const getPgs = async ()=>{  
    // console.log(useStore.pgs)    
    if(!useStore.pgs.length){
        let pgs = await getPg()
        useStore.setPgs(pgs.datas.pgs)       
    }    
}

//改变班组
const changePgs = (val)=>{
    // console.log(val)
    editForm.PGNAME = useStore.pgs.find(item => item.PERSONGROUP === val).PGNAME
}

//批量修改状态
let newStatus = ref(0) //须批量修改的指定状态
let changeDatasArrs = [] //用于存储批量修改的数据

/**
 * 处理单个设备编辑、删除
 * @param type 操作类型，add：新增，update：编辑，del：删除
 * @param row 
 */
const editJcData = (type,row) => {
    // console.log(type)
    // console.log(row)
    submitType.value = type      
    if(type === 'update') {
        drawerRef.value.open()  
        title.value = "编辑"
        editForm = row
        editForm.FINISHDATE = editForm.FINISHDATE !== "" ? dateFormat(row.FINISHDATE) : ""
        editForm.SCHEDFINISH = dateFormat(row.SCHEDFINISH)
        //存储未修改前用户信息
        oldJcData = objCopy(row,oldJcData)               
    }
    if(type === 'add') {
        drawerRef.value.open()  
        title.value = "新增"
        resetForm()
    }
    if(type === "copy"){
        drawerRef.value.open()  
        title.value = "复制"
        editForm = objCopy(row,editForm)
        editForm.WONUM = ""
        editForm.DESCRIPTION += "_副本"
        editForm.FINISHDATE = row.FINISHDATE !== "" ? dateFormat(row.FINISHDATE) : ""
        editForm.SCHEDFINISH = dateFormat(row.SCHEDFINISH)
    }
    if(type === "batchChangeStatus"){
        if(!row.length){
            msgOpen("请选择需要处理的检测记录")
        }else{             
            row.forEach(item => {
                let changeDatasArr = []
                item.STATUS = newStatus.value
                changeDatasArr.push(item.STATUS,item.WONUM)
                changeDatasArrs.push(changeDatasArr)
            })
            // console.log(changeDatasArrs)         
        }
    }
}
/******************************************************************************************************************************** */
//#endregion

//批量处理弹出层
//#region 
/***************************************************************************************************************************** */
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectJcDatas = ref([]) //选中的检测记录行数据
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "WONUM",
    "DESCRIPTION",
    "AREA",
    "AREA2",
    "ISPASS",
    "FINISHDATE",
    "PERSON",
    "PERSON2",
    "PERSON3",
    "REMARK",    
    "CUST_LINENUM",
    "CUST_SPECNUM",
    "SPEC_DESC",
    "CUST_SUBSYS",
    "SUB_DESC",
    "LOCATION",
    "PERSONGROUP",
    "PGNAME",
    "SCHEDFINISH",
    "DEVICENUM",
    "SBDESC",    
    "STATUS",
]) //上传的字段

const batchEdit = ()=>{   
    if(newDatasArr.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}

/**
 * 表格选中行数据变化时触发的方法
 * @param val 选中的设备行数据
 */
const handleSelectionChange = (val)=>{
    selectJcDatas.value = val 
}

//批量上传
let uploadTable = ref([])
const batchUpload = ()=>{
    // console.log('batchUpload');
    dialogRef.value.open()       
}

//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e)=>{    
    // console.log(e.value)       
    uploadTable = e.value   
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = ()=>{
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data,tableId,fileName)=>{
    data.length ? exportClickFromTableId(tableId,fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data,fileName)=>{  
    data?.forEach(item=>{
        // console.log(item)
        item.FINISHDATE = item.FINISHDATE.length ? dateFormat(item.FINISHDATE) : item.FINISHDATE
        item.SCHEDFINISH = item.SCHEDFINISH.length ? dateFormat(item.SCHEDFINISH) : item.SCHEDFINISH
        // console.log(item)
    }) 
    if(data.length){
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝     
        exportClickFromDatas(newData,fileName)
    }else{
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
const downloadTemplate = (tableId,fileName)=>{
    // console.log(tableId)
    exportClickFromTableId(tableId,fileName)
}
/******************************************************************************************************************************** */
//#endregion

/**
 * 提交处理
 * @param type 处理类型
 * @param data 处理数据
 */
const editSubmit = async (type,data) =>{
    // console.log(type)
    // console.log(data)
    if(type === 'batchChangeStatus'){
        if(!data.length){
            msgOpen("请选择需要处理的检测记录")
        }else{
            let res = await changeJcDataStatus(type,data)
            console.log(res)
            if(res.status){
                msgOpen(res.msg,'success')
                getJcDatas(paramsForm)
            }else{
                msgOpen(res.msg)
            }            
        }    
    }
    if(type === 'add' || type === 'update' || type === 'copy'){
        updateFormRef.value.validate(async (valid) => {
            if(!valid){
                return false
            }else{
                let res = await editJcDatas(type,data)
                console.log(res)
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                res.status ? msgOpen(res.msg,'success') : msgOpen(res.msg)
                getJcDatas(paramsForm)
                resetForm() 
            }
        })       
    }
    if(type === 'delete'){
        let res = await confirm(data.WONUM)
        if(res){
            let res = await editJcDatas(type,data)
            res.status ? msgOpen(res.msg,'success') : msgOpen(res.msg)
            getJcDatas(paramsForm)
        }
    }
    if(type === 'batchDel'){
        if(!data.length){
            msgOpen('未进行勾选，请勾选！')
        }else{
            // console.log(data)            
            let wonumsArrs = []
            data.forEach(item => {
                let wonumsArr = []
                wonumsArr.push(item.WONUM)
                wonumsArrs.push(wonumsArr)
            })
            let res = await confirmBatch(wonumsArrs.length)
            if(res){
                let res = await editManyJcDatas(type,wonumsArrs)
                res.status ? msgOpen(res.msg,'success') : msgOpen(res.msg)
                getJcDatas(paramsForm)
            }
        }
    } 
    if(type === 'batchAdd' || type === 'batchUpdate'){
        let rowsArr = ref([]) 
        let editBatchStatus = ref(true)
        for(let i = 0;i < data.length;i++){
            // console.log(data[i]);            
            if(type === 'batchUpdate' && !data[i].WONUM){
                msgOpen("更新设备，请填写WONUM！")
                editBatchStatus.value = false
                break
            }else if(type === 'batchAdd' && data[i].WONUM && data[i].FINISHDATE){
                msgOpen("新增设备，WONUM请留空！")
                editBatchStatus.value = false
                break  
            }else{
                let row
                if(type === 'batchAdd'){
                    row = Object.values(data[i]) //将对象值转成数组
                }else{
                    row = data[i] //传给后端(ORACLE也可接收数组对象，处理时SQL绑定变量须于数组对象内的KEY值一致)
                    // console.log(data[i]);                   
                }                               
                // console.log(row);
                rowsArr.value.push(row)
            }
        } 
        if(editBatchStatus.value){
            let res = await editManyJcDatas(type,rowsArr.value)
            // console.log(res)            
            dialogRef.value.close()
            uploadTable = ref([])
            res.status ? msgOpen(res.msg,'success') : msgOpen(res.msg)
            getJcDatas(paramsForm) 
        }
    }  
}

watch([uploadTable],(newTable, oldTable) => {
    // console.log(newTable[0]);
    uploadTable.value = newTable[0]
})
</script>

<style lang="less" scoped>
.params-form{
    height: 100%;
    width: 100%;
    .el-form{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-around;
        .el-form-item{
            margin-bottom: 0;
            margin-right: .1875rem;
        }
    }    
}
.el-table{
    height: 95%;
}

.batchChangeStatus{
    font-size: .625rem;
    margin-left: .625rem;
}

.submit-btn{
    margin-left:.625rem;
}
</style>